package com.xianyv.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xianyv.common.Result;
import com.xianyv.entity.AdminInfo;
import com.xianyv.entity.AuthUser;
import com.xianyv.service.AdminInfoService;
import com.xianyv.util.JwtUtils;
import com.xianyv.util.RedisUtil;
import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.authentication.PasswordEncoderParser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@RestController
public class LoginController {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AdminInfoService service;


    @PostMapping("/login")
    public Result login(@RequestBody AdminInfo adminInfo) {
        log.info("adminInfo:{}", adminInfo);

        //进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(adminInfo.getUsername(), adminInfo.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //用户认证结果

        if (Objects.isNull(authentication)) {
            throw new BadCredentialsException("账号或密码错误");
        }

        AuthUser principal = (AuthUser) authentication.getPrincipal();

        redisUtil.set(principal.getAdminInfo().getId().toString(), principal);

        String token = JwtUtils.getJwtToken(principal.getAdminInfo().getId().toString(), "id");

        return Result.success(token);
    }


    @GetMapping("/log-out")
    public Result logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUser principal = (AuthUser) authentication.getPrincipal();

        //删除redis缓存的用户信息

        redisUtil.del(principal.getAdminInfo().getId().toString());

        return Result.success("退出登入成功");

    }
}
